package com.dtwave.wechat.service.provider.core.aop;

import com.dtwave.dubbo.DubboResult;
import com.dtwave.wolf.enums.ErrorTypeEnum;
import com.dtwave.wolf.execption.InnerException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author: liuwenxiang.<br>
 * 创建时间 : 2018-12-17 下午7:01.<br>
 * 功能描述 : Aop统一异常处理.<br>
 */
@Component
@Aspect
public class ExceptionAop {

    /**
     * The logger.
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 后置通知， 对dao层抛出的异常进行统一转换.
     *
     * @throws Throwable
     * the throwable
     */
    @AfterThrowing(pointcut = "execution (public * com.dtwave.wechat.service.provider.database.dao.*.*(..))",
    throwing = "ex")
    public void operateDaoException(Exception ex) throws Throwable {
        logger.error("happen SQL error", ex);
        throw InnerException.buildDBErrorException(ex.getMessage());
    }

    /**
     * 后置通知， 对dao层抛出的异常进行统一转换.
     *
     * @throws Throwable
     * the throwable
     */
    @Around("execution (public * com.dtwave.wechat.service.provider.web..*.*(..))")
    public Object operateWebException(ProceedingJoinPoint joinPoint) {
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            if (e instanceof InnerException) {

                InnerException e1 = (InnerException) e;
                return DubboResult.buildErrorResult(e1.getErrorType(), e1.getMessage());

            } else {
                // 其他未知异常， 打印warn级别日志
                logger.warn("happen unKnow error", e);
                return DubboResult.buildErrorResult(ErrorTypeEnum.UNKNOWN_ERROR.getErrorType(), "系统错误");
            }

        }
    }
}
